package com.heima.article.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    // 前置拦截,响应前处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取用户信息
        String userId = request.getHeader("userId");
        String userName = request.getHeader("userName");
        // 判断用户id不为空
        // 将用户信息放入到本地线程缓存中
        if (!StringUtils.isEmpty(userId)) {
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            if (!StringUtils.isEmpty(userName)) {
                user.setUserName(userName);
            }
            AppThreadLocalUtil.set(user);
        }
        return true;
    }

    // 后置拦截,响应后再进行处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 释放本地线程缓存,防止内存泄露 weak引用  --> 内存溢出
        AppThreadLocalUtil.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 页面渲染
    }
}
